package com.tbw.service;

import com.tbw.NotFoundException;
import com.tbw.dao.TagRespository;
import com.tbw.entity.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class TagServiceImpl implements TagService{

    @Autowired
    private TagRespository tagRespository;

    @Override
    public Tag saveTag(Tag tag) {
        return tagRespository.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRespository.getOne(id);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRespository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRespository.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        //創建排序對象,定義排序的方向為倒序,按照blog列表的size進行排序
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        //創建pageable對象,得到第一頁
        Pageable pageable = PageRequest.of(0, size, sort);
        return tagRespository.findTop(pageable);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag tag1=tagRespository.getOne(id);
        if (tag1==null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(tag,tag1);
        return tagRespository.save(tag1);
    }

    @Override
    public void deleteTag(Long id) {
        tagRespository.deleteById(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRespository.findByName(name);
    }

    /**
     * 將字符串轉換為數組
     *
     * @param ids
     * @return
     */
    public List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            //截取字符串
            String[] idarray = ids.split(",");
            for (int i = 0; i < idarray.length; i++) {
                String rex = "^[1-9]\\d*(\\.\\d+)?$";
                if(!Pattern.compile(rex).matcher(idarray[i].trim()).find()){
                    //如果不是是数字
                    Tag t1=new Tag();
                    t1.setName(idarray[i]);
                    tagRespository.save(t1);
                    idarray[i]= String.valueOf(tagRespository.findByName(idarray[i]).getId());
                }
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    public List<Tag> listTags(String ids) {

        return tagRespository.findAllById(convertToList(ids));
    }
}
